import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

def __cv2_put_text_on_img__(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  #判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)
    fontText = ImageFont.truetype(
        "fonts/platech.ttf", textSize, encoding="utf-8")
    draw.text((left, top), text, textColor, font=fontText)
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


def draw_result(img , dict_list, is_color=False):   # 车牌结果画出来
    for result in dict_list:
        rect_area = result['rect']
        
        x,y,w,h = rect_area[0],rect_area[1],rect_area[2]-rect_area[0],rect_area[3]-rect_area[1]
        padding_w = 0.05*w
        padding_h = 0.11*h

        rect_area[0]=max(0,int(x-padding_w))
        rect_area[1]=max(0,int(y-padding_h))
        rect_area[2]=min(img.shape[1],int(rect_area[2]+padding_w))
        rect_area[3]=min(img.shape[0],int(rect_area[3]+padding_h))

        result_p = result['plateNo']
        if result['plateType']==0:#单层
            result_p+=" "+result['plateColor']
        else:                             #双层
            result_p+=" "+result['plateColor']+"双层"
        cv2.rectangle(img,(rect_area[0],rect_area[1]),(rect_area[2],rect_area[3]),(0,0,255),2) #画框
        
        labelSize = cv2.getTextSize(result_p,cv2.FONT_HERSHEY_SIMPLEX,0.5,1) #获得字体的大小
        if rect_area[0]+labelSize[0][0]>img.shape[1]:                 #防止显示的文字越界
            rect_area[0]=int(img.shape[1]-labelSize[0][0])
        img=cv2.rectangle(img,(rect_area[0],int(rect_area[1]-round(1.6*labelSize[0][1]))),(int(rect_area[0]+round(1.2*labelSize[0][0])),rect_area[1]+labelSize[1]),(255,255,255),cv2.FILLED)#画文字框,背景白色
        
        if len(result) >= 6:
            img=__cv2_put_text_on_img__(img,result_p,rect_area[0],int(rect_area[1]-round(1.6*labelSize[0][1])),(0,0,0),21)
               
    return img